<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/09 14:26
 * Blog：www.myblogs.xyz
 */

namespace app\common\model;


class Member extends Common
{
    protected $name = 'member';
    protected $pk = 'member_id';

    public function memberLists($where = '', $limit = 1, $order = '', $field = '', $whereOr = '')
    {
        $data = $this->getLists($where, $limit, $order, $field, $whereOr);
        $list = $data['list'];
        if (is_array($list)){
            $member_balance = new MemberBalance();
            foreach ($list as $key=>$val){
                $balance_data = $member_balance->getFind(['member_id'=>$val['member_id']], 'balance_id,balance,deposit,platform_balance');
                $list[$key]['balance'] = $balance_data['balance'];
                $list[$key]['deposit'] = 0;
                $list[$key]['platform_balance'] = $balance_data['platform_balance'];
                // 获取违章次数
                $list[$key]['violation_count'] = 0;
            }
        }
        $data['list'] = $list;
        return $data;
    }

    public function memberAccount()
    {
        $account = $this->order('account desc')->value('account');
        if (empty($account)) return 10000;
        return $account + 1;
    }

    // 查看账户信息
    public function showMember($member_id)
    {
        $member_data = $this->getFind($member_id);
        if (empty($member_data)) return [];
        $member_data['create_time'] = date('Y-m-d H:i:s', $member_data['create_time']);
        // 获取钱包信息
        $member_balance = new MemberBalance();
        $member_balance->fields =  'balance_id,balance,deposit,platform_balance';
        $balance_data = $member_balance->balanceFind(['member_id'=>$member_id]);
        // 获取押金信息
        $member_deposit = new MemberDeposit();
        $deposit = $member_deposit->where('member_id', $member_data['member_id'])->sum('deposit');
        $member_data['balance'] = $balance_data['balance'];
        $member_data['deposit'] = empty($deposit) ? 0.00 : floatval($deposit);
        // 获取骑行次数
        $order_model = new Order();
        $order_count = $order_model->where('member_id', $member_data['member_id'])->count();
        $member_data['order_count'] = intval($order_count);
        // 获取违章次数
        $violation_model = new Violation();
        $violation_count = $violation_model->where('member_id', $member_data['member_id'])->count();
        $member_data['violation_count'] = intval($violation_count);

        return $member_data;
    }

    // 获取用户TOKEN
    public function getWxAuth($code)
    {
        if (!empty($code)){
            // 获取用户token
            $setting_model = new Setting();
            $setting_data = $setting_model->settingFind('wx_applet');
            if (empty($setting_data)){
                return false;
            }
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $setting_data['app_id'] . '&secret=' . $setting_data['app_key'] . '&js_code=' . $code . '&grant_type=authorization_code';
            $data = file_get_contents($url);
            $json_data = json_decode($data, true);
            if (empty($json_data['openid'])){
                return false;
            }
            return $json_data;
        }
        return false;
    }

    // 验证微信授权手机号
    public function verifyWxMobile($param = [])
    {
        if (!empty($param['encryptedData']) && !empty($param['iv'])){
            if (empty($param['session_key'])) return false;
            $setting_model = new Setting();
            $setting_data = $setting_model->settingFind('wx_applet');
            if (empty($setting_data) || empty($setting_data['app_id'])){
                return false;
            }
            import('wx.wxBizDataCrypt');
            $pc = new \WXBizDataCrypt($setting_data['app_id'], $param['session_key']);
            $errCode = $pc->decryptData($param['encryptedData'], $param['iv'], $data);
            if ($errCode == 0) {
                return $data;
            }
        }
        return false;
    }

    // 用户注册
    public function memberRegister($param = [])
    {
        if (!empty($param['mobile'])){
            if ($this->getExists(['mobile'=>$param['mobile']])){
                $this->error = '该账户已经注册';
                return false;
            }
        }
        // 其他操作如发生短信，增加信息
        $param['account'] = $this->memberAccount();
        if (!empty($param['mobile']) && empty($param['nickname'])){
            $param['nickname'] = '新会员' . sub_str($param['mobile'], 7, 4);
        }
        if (empty($param['face'])){
            $param['face'] = 'default.png';
        }
        if (empty($param['create_ip'])){
            $param['create_ip'] = get_client_ip();
        }
        if (empty($param['create_time'])){
            $param['create_time'] = NEW_TIME;
        }
        $member_id = $this->insert($param, true);
        if (empty($member_id)){
            return false;
        }
        // 写入账户信息
        $member_balance = new MemberBalance();
        $member_balance->insert(['member_id'=>$member_id]);

        return true;
    }

    public function memberLogin($param, $out = false, $is_update = true)
    {
        $this->fields = 'member_id,account,nickname,mobile,email,face,sex,';
        $this->fields .= 'name,card,alias,token,is_account,status';
        if (empty($param['member_id'])){
            if (is_mobile($param['account'])){
                $member_data = $this->getFind(['mobile'=>$param['account']]);
            }else{
                $member_data = $this->getFind(['email'=>$param['account']]);
            }
        }else{
            $member_data = $this->getFind($param['member_id']);
        }
        if (empty($member_data)){
            $this->error = '该账户不存在';
            return false;
        }
        if ($member_data['status'] != 0){
            $this->error = '账户已被锁定';
            return false;
        }
        $alias = '';
        if (!empty($param['device_number'])){
            $alias = md5(base64_encode($param['device_number'] . $member_data['account']));
            // 是否有多台设备同时登录
            if (!empty($member_data['alias']) && $member_data['alias'] != $alias){
                if ($out){
                    $this->error = '您的帐户已登录到其他设备上，您被迫下线';
                    return false;
                }
            }
        }
        // 客户端类型处理
        $app_type = 1;
        if (!empty($param['app_type'])){
            $app_type = intval($param['app_type']);
            if ($app_type > 2){
                $param['app_version'] = '1.0';
            }
            if ($app_type > 4){
                $param['device_type'] = $_SERVER['HTTP_USER_AGENT'];
            }
        }
        // 同步其它基本信息
        if (!empty($param['nickname'])){
            $member_data['nickname'] = $param['nickname'];
            $save_data['nickname'] = $param['nickname'];
        }
        if (!empty($param['face'])){
            $member_data['face'] = $param['face'];
            $save_data['face'] = $param['face'];
        }
        // 记录用户活跃信息
        $active_user = new ActiveUser();
        $active_user->insertActive($member_data['member_id']);
        // 更新TOKEN信息
        $member_token = new MemberToken();
        $token = $member_token->getToken($member_data['account'], $member_data['member_id'], $is_update, $app_type);
        $member_data['alias'] = $alias;
        $member_data['token'] = $token;
        $save_data['alias'] = $alias;
        $save_data['token'] = $token;
        $save_data['last_time'] = NEW_TIME;
        $save_data['last_ip'] = get_client_ip();
        $save_data['member_id'] = $member_data['member_id'];
        $this->update($save_data);
        // 获取当前账户信息
        $member_balance = new MemberBalance();
        $balance = $member_balance->getField($member_data['member_id'], 'balance');
        $member_data['balance'] = sprintf('%.2f', floatval($balance));

        return $member_data;
    }

}